<?php

/**
 * Sites
 *
 * @author      Ian Szewczyk <roamzero@gmail.com>
 * @copyright   (c) 2007 Ian Szewczyk. All rights reserved.
 * @license     http://www.opensource.org/licenses/bsd-license.php
 * @package Modules
 * @filesource
 */

// Using a slightly modified magpierss library
require FRAMEWORK_BASE_PATH.'/Lib/magpierss/rss_fetch.inc';


/**
 * Sites
 *
 * @author Ian Szewczyk <roamzero@gmail.com>
 * @todo Add a link to view the mashup RSS
 * @package Modules
 */
class Framework_Module_Sites extends Framework_Module {


	/**
     * $navParts
     *
     * @access      private
     * @var         array		$navParts      Url parts
     */
	private $navParts = array();

	/**
	 * __construct
	 *
	 * Initializes the module: sets the default presenter, the allowed
	 * conrollers, and the allowed events
	 *
	 * @access 		public
	 * @return 		void
	 */
	public function __construct()
	{
		parent::__construct();
		if (Framework::$request->isAjax()) {
			$this->presenter = 'Module';
		 } else {
			$this->presenter = 'Smarty';
		 }
			
		$this->tplFile = 'Sites.tpl';
		// Set outer template
		$this->pageTemplateFile = 'ProfilePage.tpl';
		// Nav parts
		$this->navParts = Framework::$request->requestParts;
			
		$this->controllers[] = 'Peopletab';

			
	}

	/**
	 * __default
	 *
	 * Load "mashup" of sites that have RSS by default, otherwise just load the RSS
	 *
	 *
	 * @access 		public
	 * @todo		page the RSS results with pager
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	public function __default()
	{

		// Test for ajax request
		if(Framework::$request->isAjax()) {
			$this->presenter = 'Module';
			$this->setData('isAjax',true);
		} else {
			$this->setData('isAjax',false);
		}


		$owner = Framework_Owner::singleton();
			
		// Get the owner's sites
		$sites = $owner->getSites();
		if (!PEAR::isError($sites) && count($sites)) {
			$this->setData('sites', $sites);
			// If there is a site to view, try to get its ID
			if (strcasecmp($this->navParts[0],'view') == 0) {
				if ($this->navParts[1] && preg_match('/^[0-9]+$/i', $this->navParts[1])) {
					foreach($sites as $site) {
						if ($site['idSite'] == $this->navParts[1]) {
							try {
								$rss = fetch_rss($site['rssURL'] );
							} catch (Exception $e) {
								$errors[] = 'RSS could not be loaded';
							}
							break;
						}
							
					}
				}
					
				if($rss) {
					$this->setData('rss',$rss);
				} 
			// Otherwise try to generate an aggregate "mashup"		
			} else {
				$mashup = $this->generateMashup($sites);
				$this->setData('mashup', $mashup);
			}
		}
			
		if ($errors) {
			$this->setData('errors', $errors);
		}
			
		return true;

	}

	/**
	 * generateMashup
	 *
	 * Load "mashup" of sites that have RSS by default, otherwise just load the RSS
	 *
	 *
	 * @access 		private
	 * @param		array		$sites		Array of Owner sites
	 * @return 		mixed 		boolean true on success, PEAR_Error on failure
	 */
	private function generateMashup($sites)
	{
			
		// Check cache
		$owner = Framework_Owner::singleton();
		$cache = Framework_Cache::factory('Mashup', 7200);
		if ($entries = $cache->get($owner->idOwner)) {
			return $entries;
		}

		// Load normally
		$entries = array();
			
		foreach ($sites AS $site) {
			// load the rss
			try {
				$rss = fetch_rss($site['rssURL'] );
				// parse the dates
				if ($rss) {
					foreach($rss->items AS $item) {
						// Needs timestamp and it needs to be in the last 5 days
						if ($item['date_timestamp'] && $item['date_timestamp'] >= (time() - 432000)) {
							$date_parsed = getdate($item['date_timestamp']);
							if ($date_parsed && $date_parsed['month'] && $date_parsed['weekday'] && $date_parsed['year']) {
								$entries[mktime(null, null, null, $date_parsed['mon'], $date_parsed['mday'], $date_parsed['year'])][$site['siteName']][] = $item;
							}
						}
					}
				}

			} catch (Exception $e) {
				// Handle an error
				return PEAR::raiseError($e->message());
			}


		}
		// Sort
		//foreach($entries AS $key=>$entry) {
		//	usort($entries[$key], array($this,'cmp'));
		//}
		krsort($entries);

		// Cache
		$cache->save($entries, $owner->idOwner);

		// Return
		return $entries;
			
			
	}



}

?>